package com.meiyuetao.myt.pub.web.action;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import lab.s2jh.auth.entity.User;
import lab.s2jh.auth.service.UserService;
import lab.s2jh.core.annotation.MetaData;
import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.security.AclService;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.core.web.SimpleController;
import lab.s2jh.core.web.rest.Jackson2LibHandler;
import lab.s2jh.ctx.FreemarkerService;

import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import org.apache.struts2.rest.HttpHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.util.Assert;

import com.fasterxml.jackson.databind.ser.impl.SimpleBeanPropertyFilter;
import com.google.common.collect.Maps;
import com.meiyuetao.myt.auth.entity.UserLogin;
import com.meiyuetao.myt.auth.service.UserLoginService;
import com.meiyuetao.myt.customer.service.CustomerProfileService;
import com.meiyuetao.myt.md.entity.PersonalMessageItem;
import com.meiyuetao.myt.md.service.PersonalMessageItemService;
import com.meiyuetao.myt.sale.entity.SaleDelivery;
import com.meiyuetao.myt.sale.entity.SaleDeliveryDetail;
import com.meiyuetao.myt.sale.entity.SaleDeliveryPic;
import com.meiyuetao.myt.sale.service.BoxOrderService;
import com.meiyuetao.myt.sale.service.SaleDeliveryPicService;
import com.meiyuetao.myt.sale.service.SaleDeliveryService;
import com.opensymphony.xwork2.inject.Inject;

@MetaData("UserInfoController")
public class UserInfoController extends SimpleController {
    @Autowired
    private CustomerProfileService customerProfileService;
    @Autowired
    private UserService userService;
    @Autowired
    private BoxOrderService boxOrderService;
    @Autowired
    private AclService aclService;
    @Autowired
    private FreemarkerService freemarkerService;
    @Autowired
    private SaleDeliveryService saleDeliveryService;
    @Autowired
    private SaleDeliveryPicService saleDeliveryPicService;
    @Autowired
    private UserLoginService userLoginService;
    @Autowired
    private PersonalMessageItemService personalMessageItemService;

    private static int ROWS = 20;
    private static int PAGE = 1;

    private final Logger logger = LoggerFactory.getLogger(UserInfoController.class);

    public HttpHeaders login() {
        Map<String, Object> jsonMap = Maps.newHashMap();
        HttpServletRequest request = ServletActionContext.getRequest();
        String signinid = request.getParameter("login_id");
        String password = request.getParameter("password");
        if (StringUtils.isBlank(signinid) || StringUtils.isBlank(password)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id或password");
        } else {
            Boolean exist = userService.validatePassword(signinid, password);
            if (!exist) {
                jsonMap.put("state", "110");
                jsonMap.put("message", "用户名或密码错误");
            } else {
                GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.EQ, "signinid", signinid));
                Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.filterOutAllExcept("id", "signinid", "nick"));
                List<User> users = userService.findByFilters(groupPropertyFilter);
                Assert.isTrue(users.size() <= 1);
                UserLogin userLogin = userLoginService.findByProperty("user", users.get(0));
                if (userLogin == null) {
                    userLogin = new UserLogin();
                    userLogin.setUser(users.get(0));

                }
                userLogin.setLastLoginTime(new Date());
                userLogin.setLastOperateTime(new Date());
                String randomCode = new SimpleDateFormat("yyMMddHHmmSS").format(new Date()) + RandomStringUtils.randomNumeric(3);
                userLogin.setRandomCode(randomCode);
                userLoginService.save(userLogin);
                jsonMap.put("state", "200");
                jsonMap.put("data", users.get(0));
                jsonMap.put("token", randomCode);

            }
        }
        /*
         * User user =
         * userService.findBySigninid(request.getParameter("login_id"));
         * UserLogin userLogin = userLoginService.findByProperty("user", user);
         * if (userLogin == null) { userLogin = new UserLogin();
         * userLogin.setUser(user);
         * 
         * } userLogin.setLastLoginTime(new Date());
         * userLogin.setLastOperateTime(new Date()); String randomCode = new
         * SimpleDateFormat("yyMMddHHmmSS") +
         * RandomStringUtils.randomNumeric(3);
         * userLogin.setRandomCode(randomCode);
         * userLoginService.save(userLogin); jsonMap.put("state", "200");
         * jsonMap.put("data", user); jsonMap.put("token", randomCode);
         */
        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders logout() {
        Map<String, Object> jsonMap = Maps.newHashMap();
        HttpServletRequest request = ServletActionContext.getRequest();
        String signinid = request.getParameter("login_id");
        if (StringUtils.isBlank(signinid)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id");
        }
        try {
            User user = userService.findBySigninid(signinid);
            UserLogin userLogin = userLoginService.findByProperty("user", user);
            if (userLogin == null) {
                userLogin = new UserLogin();
                userLogin.setUser(user);

            }
            userLogin.setLastOperateTime(new Date());
            userLogin.setRandomCode("LOGOUT");
            userLoginService.save(userLogin);
            jsonMap.put("state", "200");
            jsonMap.put("message", "已注销");
        } catch (Exception e) {
            jsonMap.put("state", "600");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }
        setModel(jsonMap);
        return buildDefaultHttpHeaders();

    }

    public HttpHeaders personalMessage() {
        Map<String, Object> jsonMap = Maps.newHashMap();
        HttpServletRequest request = ServletActionContext.getRequest();
        String signinid = request.getParameter("login_id");
        if (StringUtils.isBlank(signinid)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        User user = userService.findBySigninid(signinid);
        if (!accountEffective(user)) {
            jsonMap.put("state", "500");
            jsonMap.put("token", "EXPIRED");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        // List<PersonalMessageItem> personalMessageItems;
        try {
            int rows;
            int page;
            if (StringUtils.isBlank(request.getParameter("rows"))) {
                rows = ROWS;
            } else {
                rows = Integer.valueOf(request.getParameter("rows"));
            }
            if (StringUtils.isBlank(request.getParameter("page"))) {
                page = PAGE;
            } else {
                page = Integer.valueOf(request.getParameter("page"));
            }
            Pageable pageable = new PageRequest(page - 1, rows, new Sort(Direction.DESC, "createdDate"));
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildFromHttpRequest(PersonalMessageItem.class, request);
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.EQ, "targetUser", user));
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.EQ, "enable", true));
            /*
             * Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.
             * filterOutAllExcept("id", "personalMessage", "title", "contents",
             * "createdDate"));
             */
            Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.filterOutAllExcept("createdDate", "personalMessage", "title", "contents"));
            /*
             * personalMessageItems =
             * personalMessageItemService.findByFilters(groupPropertyFilter, new
             * Sort( Direction.DESC, "createdDate"));
             */
            Page<PersonalMessageItem> personalMessageItems = personalMessageItemService.findByPage(groupPropertyFilter, pageable);

            updateUserLoginOperateTime(user);
            jsonMap.put("state", "200");
            jsonMap.put("data", personalMessageItems);
        } catch (Exception e) {
            jsonMap.put("state", "600");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }
        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    private Boolean accountEffective(User user) {
        UserLogin userLogin = userLoginService.findByProperty("user", user);
        if (userLogin == null) {
            return false;
        }
        if (("LOGOUT").equals(userLogin.getRandomCode())) {
            return false;
        }
        Date lastOperateTime = userLogin.getLastOperateTime();
        Calendar remindDate = Calendar.getInstance();
        remindDate.setTime(new Date());
        remindDate.add(Calendar.HOUR_OF_DAY, -2);
        if (lastOperateTime.before(remindDate.getTime())) {
            return false;
        }
        return true;
    }

    private Boolean saleDeliveryEffective(User user, String voucher) {
        SaleDelivery saleDelivery = saleDeliveryService.findByProperty("voucher", voucher);
        if (saleDelivery == null) {
            return false;
        } else {
            // 限定只能访问登录用户所在商家的数据
            String aclCodePrefix = aclService.getAclCodePrefix(user.getAclCode());
            if (StringUtils.isNotBlank(aclCodePrefix) && !saleDelivery.getAgentPartner().getCode().startsWith(aclCodePrefix)) {
                return false;
            }
        }
        return true;
    }

    public HttpHeaders saleDeliverys() {
        Map<String, Object> jsonMap = Maps.newHashMap();
        HttpServletRequest request = ServletActionContext.getRequest();
        String signinid = request.getParameter("login_id");
        if (StringUtils.isBlank(signinid)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        User user = userService.findBySigninid(signinid);
        if (!accountEffective(user)) {
            jsonMap.put("state", "500");
            // jsonMap.put("data", user);
            jsonMap.put("token", "EXPIRED");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        List<SaleDelivery> saleDeliverys;
        try {
            GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NN, "auditDate", true));
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NU, "redwordDate", true));
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.NN, "agentAcceptDate", true));
            // 限制只显示指派时间小于当前时间的单子
            groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.LT, "agentAssignDate", new Date()));
            // 限定只能访问登录用户所在商家的数据
            String aclCodePrefix = aclService.getAclCodePrefix(user.getAclCode());
            if (StringUtils.isNotBlank(aclCodePrefix)) {
                groupPropertyFilter.forceAnd(new PropertyFilter(MatchType.BW, "agentPartner.code", aclCodePrefix));
            }
            Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.filterOutAllExcept("id", "voucher", "reserveDeliveryTime", "receivePerson", "logisticsNo",
                    "mobilePhone", "deliveryAddr", "logisticsAmount", "processType"));
            saleDeliverys = saleDeliveryService.findByFilters(groupPropertyFilter);
            updateUserLoginOperateTime(user);

            jsonMap.put("state", "200");
            jsonMap.put("data", saleDeliverys);
        } catch (Exception e) {
            jsonMap.put("state", "600");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }
        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders saleDeliveryDetails() {

        HttpServletRequest request = ServletActionContext.getRequest();
        Map<String, Object> jsonMap = Maps.newHashMap();
        /*
         * String signinid = request.getParameter("loginId"); String password =
         * request.getParameter("password"); User user = null; if
         * (StringUtils.isBlank(signinid) || StringUtils.isBlank(password)) {
         * jsonMap.put("state", "100"); jsonMap.put("message", "登录名或密码不能为空");
         * setModel(jsonMap); return buildDefaultHttpHeaders(); } else { Boolean
         * exist = userService.validatePassword(signinid, password); if (!exist)
         * { jsonMap.put("state", "400"); jsonMap.put("message", "用户名或密码错误");
         * setModel(jsonMap); return buildDefaultHttpHeaders(); } else { user =
         * userService.findBySigninid(signinid); } }
         */
        String signinid = request.getParameter("login_id");
        if (StringUtils.isBlank(signinid)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        User user = userService.findBySigninid(signinid);
        if (!accountEffective(user)) {
            jsonMap.put("state", "500");
            // jsonMap.put("data", user);
            jsonMap.put("token", "EXPIRED");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        String voucher = request.getParameter("voucher");
        if (StringUtils.isBlank(voucher)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：voucher");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        if (!saleDeliveryEffective(user, voucher)) {
            jsonMap.put("state", "500");
            jsonMap.put("message", "无效的单号");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        /*
         * SaleDelivery saleDelivery =
         * saleDeliveryService.findOne(Long.valueOf(saleDeliveryId)); if
         * (saleDelivery == null) { jsonMap.put("state", "120");
         * jsonMap.put("message", "没有查到此销售单"); setModel(jsonMap); return
         * buildDefaultHttpHeaders(); } else { //限定只能访问登录用户所在商家的数据 String
         * aclCodePrefix = aclService.getAclCodePrefix(user.getAclCode()); if
         * (StringUtils.isNotBlank(aclCodePrefix) &&
         * !saleDelivery.getAgentPartner().getCode().startsWith(aclCodePrefix))
         * { jsonMap.put("state", "300"); jsonMap.put("message", "销售单无权访问");
         * setModel(jsonMap); return buildDefaultHttpHeaders(); } }
         */
        List<SaleDeliveryDetail> saleDeliveryDetails;
        try {
            SaleDelivery saleDelivery = saleDeliveryService.findByProperty("voucher", voucher);
            Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.filterOutAllExcept("id", "measureUnit", "quantity", "commodity", "sku", "title", "smallPic"));
            saleDeliveryDetails = saleDelivery.getSaleDeliveryDetails();
            updateUserLoginOperateTime(user);
            jsonMap.put("state", "200");
            jsonMap.put("data", saleDeliveryDetails);
        } catch (Exception e) {
            jsonMap.put("state", "600");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }

        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    public HttpHeaders saleDeliveryPics() {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map<String, Object> jsonMap = Maps.newHashMap();

        String signinid = request.getParameter("login_id");
        if (StringUtils.isBlank(signinid)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        User user = userService.findBySigninid(signinid);
        if (!accountEffective(user)) {
            jsonMap.put("state", "500");
            // jsonMap.put("data", user);
            jsonMap.put("token", "EXPIRED");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        String voucher = request.getParameter("voucher");
        if (StringUtils.isBlank(voucher)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：voucher");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        if (!saleDeliveryEffective(user, voucher)) {
            jsonMap.put("state", "500");
            jsonMap.put("message", "无效的单号");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        List<SaleDeliveryPic> saleDeliveryPics;
        try {
            SaleDelivery saleDelivery = saleDeliveryService.findByProperty("voucher", voucher);
            Jackson2LibHandler.setJsonPropertyFilter(SimpleBeanPropertyFilter.filterOutAllExcept("id", "picUrl", "picIndex"));
            saleDeliveryPics = saleDelivery.getSaleDeliveryPics();
            updateUserLoginOperateTime(user);
            jsonMap.put("state", "200");
            jsonMap.put("data", saleDeliveryPics);
        } catch (Exception e) {
            jsonMap.put("state", "600");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }

        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    /* private File[] files; */

    public HttpHeaders saleDeliverySave() {
        HttpServletRequest request = ServletActionContext.getRequest();
        Map<String, Object> jsonMap = Maps.newHashMap();
        String signinid = request.getParameter("login_id");
        if (StringUtils.isBlank(signinid)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：login_id");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        User user = userService.findBySigninid(signinid);
        if (!accountEffective(user)) {
            jsonMap.put("state", "500");
            // jsonMap.put("data", user);
            jsonMap.put("token", "EXPIRED");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        String voucher = request.getParameter("voucher");
        if (StringUtils.isBlank(voucher)) {
            jsonMap.put("state", "100");
            jsonMap.put("message", "缺少参数：voucher");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        if (!saleDeliveryEffective(user, voucher)) {
            jsonMap.put("state", "500");
            jsonMap.put("message", "无效的单号");
            setModel(jsonMap);
            return buildDefaultHttpHeaders();
        }
        List<Map<String, Object>> responseList = new ArrayList<Map<String, Object>>();
        try {
            SaleDelivery saleDelivery = saleDeliveryService.findByProperty("voucher", voucher);
            List<SaleDeliveryPic> saleDeliveryPics = new ArrayList<SaleDeliveryPic>();
            MultiPartRequestWrapper wrapper = (MultiPartRequestWrapper) request;

            // File[] files = wrapper.getFiles("imgFile");
            File[] files = getFiles(wrapper);
            if (files != null && files.length > 0) {
                GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
                groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "saleDelivery", saleDelivery));
                List<SaleDeliveryPic> saleDeliveryPicList = saleDeliveryPicService.findByFilters(groupPropertyFilter);
                saleDeliveryPicService.delete(saleDeliveryPicList);

            }
            if (StringUtils.isNotBlank(request.getParameter("logisticsNo"))) {
                saleDelivery.setLogisticsNo(request.getParameter("logisticsNo"));
                saleDelivery.setLastOperationSummary(user.getSigninid() + "拍照上传" + ":" + DateUtils.formatTimeNow());
                saleDelivery = saleDeliveryService.save(saleDelivery);
                Map<String, Object> retMap = Maps.newHashMap();
                retMap.put("logisticsNo", "true");
                retMap.put("value", request.getParameter("logisticsNo"));
                responseList.add(retMap);
            }
            int i = 0;
            if (files != null && files.length > 0) {
                for (File file : files) {
                    if (file != null) {
                        Map<String, Object> infoMap = imageUpload(file);
                        if (infoMap.get("error").equals(0)) {
                            SaleDeliveryPic saleDeliveryPic = new SaleDeliveryPic();
                            saleDeliveryPic.setPicUrl((String) infoMap.get("md5"));
                            saleDeliveryPic.setPicIndex(1000 - 100 * i);
                            saleDeliveryPic.setSaleDelivery(saleDelivery);
                            saleDeliveryPicService.save(saleDeliveryPic);
                            saleDeliveryPics.add(saleDeliveryPic);
                        }
                        i++;
                        responseList.add(infoMap);
                    }

                }
            }
            updateUserLoginOperateTime(user);
            jsonMap.put("state", "200");
            jsonMap.put("data", responseList);
        } catch (Exception e) {
            jsonMap.put("state", "600");
            jsonMap.put("message", "System Errror");
            logger.error("System Errror", e);
        }
        setModel(jsonMap);
        return buildDefaultHttpHeaders();
    }

    private File[] getFiles(MultiPartRequestWrapper wrapper) {
        File[] files = new File[100];
        List<File> fileList = new ArrayList<File>();
        for (int i = 1; i <= 100; i++) {
            File[] ifiles = wrapper.getFiles("imgFile" + i);
            if (ifiles != null && ifiles.length > 0) {
                for (File file : ifiles) {
                    fileList.add(file);
                }
            }

        }
        int i = 0;
        for (File file : fileList) {
            if (file != null) {
                files[i++] = file;
            }

        }
        return files;
    }

    protected long imageUploadMaxSize;

    @Inject("struts.multipart.maxSize")
    public void setImageUploadMaxSize(String imageUploadMaxSize) {
        this.imageUploadMaxSize = Long.parseLong(imageUploadMaxSize);
    }

    public Map<String, Object> imageUpload(File file) {
        Map<String, Object> retMap = Maps.newHashMap();
        CloseableHttpClient httpclient = HttpClients.createDefault();
        try {
            if (file.length() > imageUploadMaxSize) {
                retMap.put("error", 1);
                retMap.put("message", "文件大小超过限制:" + imageUploadMaxSize);
            } else {
                String targetURL = "http://img5.iyoubox.com/PutLocalFile.aspx";
                HttpPost post = new HttpPost(targetURL);
                FileBody fileBody = new FileBody(file);
                HttpEntity httpEntity = MultipartEntityBuilder.create().addPart("file", fileBody).build();
                post.setEntity(httpEntity);
                CloseableHttpResponse httpResponse = httpclient.execute(post);
                int status = httpResponse.getStatusLine().getStatusCode();
                String responseBody = EntityUtils.toString(httpResponse.getEntity());
                if (HttpStatus.SC_OK == status) {
                    logger.debug("Upload complete, response={}", responseBody);
                    String message = responseBody.substring(2);
                    if (responseBody.startsWith("1+")) {
                        retMap.put("error", 0);
                        retMap.put("url", "http://img.iyoubox.com/GetFileByCode.aspx?code=" + message);
                        retMap.put("md5", message);
                    } else {
                        retMap.put("error", 1);
                        retMap.put("message", message);
                    }
                } else {
                    logger.error("Upload failed, status={}, response={}", status, responseBody);
                    retMap.put("error", 1);
                    retMap.put("message", "Error Status:" + status);
                }
                httpResponse.close();
            }

        } catch (Exception ex) {
            retMap.put("error", 1);
            retMap.put("message", "System Errror");
            logger.error("error.file.upload", ex);
        } finally {
            try {
                httpclient.close();
            } catch (IOException e) {
                retMap.put("error", 1);
                retMap.put("message", "System Errror");
                logger.error("error.httpclient", e);
            }
        }
        return retMap;
    }

    /*
     * public HttpHeaders customerData() { Map<String, Object> jsonMap =
     * Maps.newHashMap(); ObjectMapper objectMapper =
     * HibernateAwareObjectMapper.getInstance(); HttpServletRequest request =
     * ServletActionContext.getRequest(); String mobile =
     * request.getParameter("mobile"); if (StringUtils.isNotBlank(mobile)) {
     * //取得 GroupPropertyFilter groupPropertyFilter1 =
     * GroupPropertyFilter.buildDefaultAndGroupFilter();
     * groupPropertyFilter1.append(new PropertyFilter(MatchType.EQ,
     * "mobilePhone", mobile)); List<CustomerProfile> customerProfiles =
     * customerProfileService.findByFilters(groupPropertyFilter1);
     * 
     * GroupPropertyFilter groupPropertyFilter2 =
     * GroupPropertyFilter.buildDefaultAndGroupFilter();
     * groupPropertyFilter2.append(new PropertyFilter(MatchType.EQ,
     * "mobilePhone", mobile)); List<BoxOrder> boxOrders2 =
     * boxOrderService.findByFilters(groupPropertyFilter2);
     * 
     * GroupPropertyFilter groupPropertyFilter3 =
     * GroupPropertyFilter.buildDefaultAndGroupFilter();
     * groupPropertyFilter3.append(new PropertyFilter(MatchType.FETCH,
     * "customerProfile", "INNER")); groupPropertyFilter3.append(new
     * PropertyFilter(MatchType.EQ, "customerProfile.mobilePhone", mobile));
     * List<BoxOrder> boxOrders3 =
     * boxOrderService.findByFilters(groupPropertyFilter3); Set<BoxOrder>
     * boxOrders1 = Sets.newHashSet(); boxOrders1.addAll(boxOrders2);
     * boxOrders1.addAll(boxOrders3); List<BoxOrder> boxOrders = new
     * ArrayList<BoxOrder>(boxOrders1); Collections.sort(boxOrders, new
     * Comparator<BoxOrder>() { public int compare(BoxOrder o1, BoxOrder o2) {
     * return o2.getOrderTime().compareTo(o1.getOrderTime()); } }); String sid =
     * ""; jsonMap.put("success", "200"); jsonMap.put("message",
     * boxOrders.size());
     * 
     * String jsoString = null; try { jsoString =
     * objectMapper.writeValueAsString(jsonMap); } catch
     * (JsonProcessingException e) { e.printStackTrace(); } setModel(jsoString);
     * } else { jsonMap.put("error", "100"); jsonMap.put("message",
     * "miss parameter 'mobile'"); String jsoString = null; try { jsoString =
     * objectMapper.writeValueAsString(jsonMap); } catch
     * (JsonProcessingException e) { e.printStackTrace(); } setModel(jsoString);
     * } return buildDefaultHttpHeaders(); }
     */

    private void updateUserLoginOperateTime(User user) {
        UserLogin userLogin = userLoginService.findByProperty("user", user);
        userLogin.setLastOperateTime(new Date());
        userLoginService.save(userLogin);
    }

}